package org.alwayssuper.protocol.commons.transform.realtimev2016;

import org.alwayssuper.protostar.annotation.Field;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

import java.util.List;

/**
 * 2016版可充电储能装置温度数据格式 (0x09)
 * 参考GBT32960协议和ReportDecoder解析规则
 * @author alwaysSuper
 */
@ToString
@Data
@Accessors(chain = true)
public class BatteryTemperatureData {
    
    @Field(totalUnit = 1, desc = "可充电储能装置子系统列表")
    private List<ChargeableSubsystemTemperature> subsystemList;

    @ToString
    @Data
    @Accessors(chain = true)
    public static class ChargeableSubsystemTemperature {
        
        @Field(length = 1, desc = "可充电储能子系统号:1~250")
        private int subsystemNumber;
        
        @Field(totalUnit = 2, desc = "可充电储能装置温度探针列表")
        private List<ProbeTemperature> probeTemperatureList;
        
        /**
         * 获取探针温度列表中对应的温度值数组
         */
        public double[] getTemperatures() {
            if (probeTemperatureList == null) {
                return new double[0];
            }
            return probeTemperatureList.stream()
                    .mapToDouble(ProbeTemperature::getTemperature)
                    .toArray();
        }
        
        /**
         * 获取探针数量
         */
        public int getProbeCount() {
            return probeTemperatureList == null ? 0 : probeTemperatureList.size();
        }
    }
    
    @ToString
    @Data
    @Accessors(chain = true)
    public static class ProbeTemperature {
        
        @Field(length = 1, desc = "可充电储能装置温度探针温度值:-40℃~210℃,偏移40℃")
        private int temperature;
        
        /**
         * 获取温度值 (℃)
         * 传输值范围: 0~250, 偏移量40℃, 表示 -40℃~+210℃, 精度 1℃
         * 0xFE: 异常, 0xFF: 无效
         */
        public double getTemperature() {
            if (temperature == 0xFE || temperature == 0xFF) {
                return Double.NaN;
            }
            return temperature - 40.0;
        }
        
        /**
         * 设置温度值 (℃)
         * 值范围: -40℃~+210℃
         */
        public void setTemperature(double temperature) {
            if (Double.isNaN(temperature) || temperature < -40.0 || temperature > 210.0) {
                this.temperature = 0xFF; // 无效
            } else {
                this.temperature = (int) Math.round(temperature + 40);
            }
        }
    }
    
    // 通过subsystemList列表长度返回子系统数量
    public int getSubsystemCount() {
        return subsystemList == null ? 0 : subsystemList.size();
    }
}